package com.hzy.fivepalace.db.service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import javax.annotation.Resource;

import com.hzy.fivepalace.common.type.OrderStatusEnums;
import com.hzy.fivepalace.db.bean.CategorySellAmts;
import com.hzy.fivepalace.db.bean.DayStatis;
import com.hzy.fivepalace.db.dao.DtsOrderMapper;
import com.hzy.fivepalace.db.dao.ex.OrderMapper;
import com.hzy.fivepalace.db.dao.ex.StatMapper;
import com.hzy.fivepalace.db.domain.DtsOrder;
import com.hzy.fivepalace.db.domain.DtsOrderExample;
import com.hzy.fivepalace.db.domain.DtsOrderWithBLOBs;
import com.hzy.fivepalace.db.service.base.BaseService;
import com.hzy.fivepalace.db.util.OrderUtil;
import jodd.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.PageHelper;

@Service
public class DtsOrderService {
    @Resource
    private DtsOrderMapper dtsOrderMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private StatMapper statMapper;

    /**
     * 获取某一个用户他推广的某一个会员总数
     * @param userId
     * @param vipType
     * @return
     */
    public Integer getUserVipSumExtendCount(Integer userId,Integer vipType){
       Integer count= orderMapper.getUserVipSumExtendCount(userId,vipType);
       return null==count?0:count;
    }


    /**
     * 根据订单id获取商品名称
     *
     * @param orderId
     * @return
     */
    public String getGoodsNameByOrderId(Integer orderId) {
        String goodsName = orderMapper.getGoodsNameByOrderId(orderId);
        return StringUtil.isBlank(goodsName)?"实物商品":goodsName;
    }

    public DtsOrderWithBLOBs findByIdAndUserId(Integer orderId, Integer userId) {
        DtsOrderExample example = new DtsOrderExample();
        //不查系统取消的订单
        example.createCriteria().andIdEqualTo(orderId).andUserIdEqualTo(userId).andDeletedEqualTo(false);
        return dtsOrderMapper.selectOneByExampleWithBLOBs(example);
    }

    public DtsOrderWithBLOBs findById(Integer orderId) {
        DtsOrderExample example = new DtsOrderExample();
        //不查系统取消的订单
        example.createCriteria().andIdEqualTo(orderId).andDeletedEqualTo(false);
        return dtsOrderMapper.selectOneByExampleWithBLOBs(example);
    }

    public int add(DtsOrderWithBLOBs order) {
        order.setAddTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        return dtsOrderMapper.insertSelective(order);
    }

    public int count(Integer userId) {
        DtsOrderExample example = new DtsOrderExample();
        example.or().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        return (int) dtsOrderMapper.countByExample(example);
    }

    public DtsOrder selectAppOrderByOrderNo(String orderNo) {
        DtsOrderExample example = new DtsOrderExample();
        example.createCriteria().andOrderSnEqualTo(orderNo);
        return dtsOrderMapper.selectOneByExample(example);
    }


    public DtsOrder selectAppOrderByOrderNoOrOutTradeNo(String orderNo) {
        return dtsOrderMapper.selectAppOrderByOrderNoOrOutTradeNo(orderNo);
    }

    public DtsOrderWithBLOBs selectOrderWithBLOBsByOrderNo(String orderNo) {
        DtsOrderExample example = new DtsOrderExample();
        example.createCriteria().andOrderSnEqualTo(orderNo);
        return dtsOrderMapper.selectOneByExampleWithBLOBs(example);
    }


    /**
     * 获取订单列表（后台管理）
     * @param statusList
     * @param phone
     * @param userId
     * @param name
     * @param orderSn
     * @return
     */
    public List<DtsOrderWithBLOBs> getOrderList(List<Short> statusList, String phone, Integer userId,String name ,String orderSn,String orderByStr) {
        DtsOrderExample example = new DtsOrderExample();
        if(StringUtils.isBlank(orderByStr)){
            example.orderBy("add_time desc");
        }else{
            example.orderBy(orderByStr);
        }

        DtsOrderExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (!CollectionUtils.isEmpty(statusList)) {
            criteria.andOrderStatusIn(statusList);
        }
        if (!StringUtil.isBlank(phone)) {
            criteria.andMobileEqualTo(phone);
        }
        if (null != userId) {
            criteria.andUserIdEqualTo(userId);
        }
        if (!StringUtil.isBlank(name)) {
            criteria.andConsigneeEqualTo(name);
        }
        if (!StringUtil.isBlank(orderSn)) {
            criteria.andOrderSnEqualTo(orderSn);
        }
        criteria.andIsByVipEqualTo(false);
        example.or(criteria);
        return dtsOrderMapper.selectByExampleWithBLOBs(example);
    }


    /**
     * 获取用户订单列表
     *
     * @param userId
     * @param status 状态:为空就查所有,新增-1状态(查售后订单列表)
     * @return
     */
    public List<DtsOrderWithBLOBs> getUserOrderList(Integer userId, Integer status) {
        DtsOrderExample example = new DtsOrderExample();

        if (null != status) {
            if(status.intValue()==-1){//为-1就是查售后订单列表
                example.orderBy("update_time desc,add_time desc");
                List<Short> statusList=new ArrayList<>();
                statusList.add((short)OrderStatusEnums.TYPE7.getType());//退款处理中
                statusList.add((short)OrderStatusEnums.TYPE8.getType());//售后审核中
                statusList.add((short)OrderStatusEnums.TYPE10.getType());//售后完成-已退款
                statusList.add((short)OrderStatusEnums.TYPE11.getType());//待上传物流信息
                statusList.add((short)OrderStatusEnums.TYPE12.getType());//待商家收货
                example.createCriteria().andUserIdEqualTo(userId).andOrderStatusIn(statusList).andDeletedEqualTo(false);
            }else{
                example.orderBy("add_time desc");
                example.createCriteria().andUserIdEqualTo(userId).andOrderStatusEqualTo(status.shortValue()).andDeletedEqualTo(false);
            }

        } else {
            example.orderBy("add_time desc");
            example.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        }
        return dtsOrderMapper.selectByExampleWithBLOBs(example);
    }

    /**
     * 获取用户订单状态数量
     *
     * @param userId
     * @param status
     * @return
     */
    public int getUserOrderCount(Integer userId, Integer status) {
        if(null==userId){//未登录返回0
            return 0;
        }
        DtsOrderExample example = new DtsOrderExample();
        example.createCriteria().andUserIdEqualTo(userId).andOrderStatusEqualTo(status.shortValue()).andDeletedEqualTo(false);
        return (int) dtsOrderMapper.countByExample(example);
    }

    /**
     * 获取用户售后中订单数量
     * @param userId
     * @return
     */
    public int getUserAfterSaleOrderCount(Integer userId) {
        if(null==userId){//未登录返回0
            return 0;
        }
        List<Short> statusList=new ArrayList<>();
        statusList.add((short)OrderStatusEnums.TYPE7.getType());//退款处理中
        statusList.add((short)OrderStatusEnums.TYPE8.getType());//售后审核中
        statusList.add((short)OrderStatusEnums.TYPE11.getType());//待上传物流信息
        statusList.add((short)OrderStatusEnums.TYPE12.getType());//待商家收货
        DtsOrderExample example = new DtsOrderExample();
        example.createCriteria().andUserIdEqualTo(userId).andOrderStatusIn(statusList).andDeletedEqualTo(false);
        return (int) dtsOrderMapper.countByExample(example);
    }


    private String getRandomNum(Integer num) {
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < num; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public int countByOrderSn(Integer userId, String orderSn) {
        DtsOrderExample example = new DtsOrderExample();
        example.or().andUserIdEqualTo(userId).andOrderSnEqualTo(orderSn).andDeletedEqualTo(false);
        return (int) dtsOrderMapper.countByExample(example);
    }

    // TODO 这里应该产生一个唯一的订单，但是实际上这里仍然存在两个订单相同的可能性
    public String generateOrderSn(Integer userId) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        String now = df.format(LocalDate.now());
        String orderSn = now + getRandomNum(6);
        while (countByOrderSn(userId, orderSn) != 0) {
            orderSn = getRandomNum(6);
        }
        return orderSn;
    }

    public List<DtsOrder> queryByOrderStatus(Integer userId, List<Short> orderStatus, Integer page, Integer size) {
        DtsOrderExample example = new DtsOrderExample();
        example.setOrderByClause(DtsOrder.Column.addTime.desc());
        DtsOrderExample.Criteria criteria = example.or();
        criteria.andUserIdEqualTo(userId);
        if (orderStatus != null) {
            criteria.andOrderStatusIn(orderStatus);
        }
        criteria.andDeletedEqualTo(false);
        PageHelper.startPage(page, size);
        return dtsOrderMapper.selectByExample(example);
    }

    public List<DtsOrder> querySelective(Integer userId, String orderSn, List<Short> orderStatusArray, Integer page,
                                         Integer size, String sort, String order) {
        DtsOrderExample example = new DtsOrderExample();
        DtsOrderExample.Criteria criteria = example.createCriteria();

        if (userId != null) {
            criteria.andUserIdEqualTo(userId);
        }
        if (!StringUtils.isEmpty(orderSn)) {
            criteria.andOrderSnEqualTo(orderSn);
        }
        if (orderStatusArray != null && orderStatusArray.size() != 0) {
            criteria.andOrderStatusIn(orderStatusArray);
        }
        criteria.andDeletedEqualTo(false);

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        PageHelper.startPage(page, size);
        return dtsOrderMapper.selectByExample(example);
    }

    public int updateWithOptimisticLocker(DtsOrder order) {
        LocalDateTime preUpdateTime = order.getUpdateTime();
        order.setUpdateTime(LocalDateTime.now());
        return orderMapper.updateWithOptimisticLocker(preUpdateTime, order);
    }

    public int updateById(DtsOrderWithBLOBs order) {
        return dtsOrderMapper.updateByPrimaryKeySelective(order);
    }

    public int addVipSales(Integer vipType) {
        return orderMapper.addVipSales( vipType);
    }

    public void deleteById(Integer id) {
        dtsOrderMapper.logicalDeleteByPrimaryKey(id);
    }

    public int count() {
        DtsOrderExample example = new DtsOrderExample();
        example.or().andDeletedEqualTo(false);
        return (int) dtsOrderMapper.countByExample(example);
    }

    public List<DtsOrder> queryUnpaid() {
        DtsOrderExample example = new DtsOrderExample();
        example.or().andOrderStatusEqualTo(OrderUtil.STATUS_CREATE).andDeletedEqualTo(false);
        return dtsOrderMapper.selectByExample(example);
    }

    public List<DtsOrder> queryUnconfirm() {
        DtsOrderExample example = new DtsOrderExample();
        example.or().andOrderStatusEqualTo(OrderUtil.STATUS_SHIP).andShipTimeIsNotNull().andDeletedEqualTo(false);
        return dtsOrderMapper.selectByExample(example);
    }

    public DtsOrder findBySn(String orderSn) {
        DtsOrderExample example = new DtsOrderExample();
        example.or().andOrderSnEqualTo(orderSn).andDeletedEqualTo(false);
        return dtsOrderMapper.selectOneByExample(example);
    }


    public List<DtsOrder> queryComment() {
        DtsOrderExample example = new DtsOrderExample();
        example.or().andCommentsGreaterThan((short) 0).andDeletedEqualTo(false);
        return dtsOrderMapper.selectByExample(example);
    }

    public List<DayStatis> recentCount(int statisDaysRang) {
        return statMapper.statisIncreaseOrderCnt(statisDaysRang);
    }

    public List<CategorySellAmts> categorySell() {
        return statMapper.categorySellStatis();
    }

    /**
     * 获取指定店铺的订单
     *
     * @param brandIds
     * @param userId
     * @param orderSn
     * @param orderStatusArray
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @return
     */
    public List<DtsOrder> queryBrandSelective(List<Integer> brandIds, Integer userId, String orderSn,
                                              List<Short> orderStatusArray, Integer page, Integer size, String sort, String order) {

        String orderStatusSql = null;
        if (orderStatusArray != null) {
            orderStatusSql = "";
            for (Short orderStatus : orderStatusArray) {
                orderStatusSql += "," + orderStatus;
            }
            orderStatusSql = "and o.order_status in (" + orderStatusSql.substring(1) + ") ";
        }

        String orderBySql = null;
        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            orderBySql = "o." + sort + " " + order;
        }

        String brandIdsSql = null;
        if (brandIds != null) {
            brandIdsSql = "";
            for (Integer brandId : brandIds) {
                brandIdsSql += "," + brandId;
            }
            brandIdsSql = " and g.brand_id in (" + brandIdsSql.substring(1) + ") ";
        }

        PageHelper.startPage(page, size);
        return orderMapper.selectBrandOrdersByExample(userId, orderSn, orderStatusSql, orderBySql, brandIdsSql);
    }

}
